package com.validant.enigma3.reports;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.velocity.VelocityContext;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.uncommons.reportng.HTMLReporter;

import com.validant.enigma3.common.Constants;
import com.validant.enigma3.common.Utils;

public class ScreenshotHTMLReporter extends HTMLReporter implements ITestListener{
	
	protected static final ScreenshotReportNGUtils SS_UTILS = new ScreenshotReportNGUtils();
	
	 /* (non-Javadoc)
     * @see org.uncommons.reportng.AbstractReporter#createContext()
     * override to use a custom utils class
     */
    protected VelocityContext createContext() {
        VelocityContext context = super.createContext();
        // UTILS_KEY is private
        context.put("utils", SS_UTILS);
        return context;
    }

	public void onFinish(ITestContext arg0) {
		// TODO Auto-generated method stub
		
	}

	public void onStart(ITestContext arg0) {
		// TODO Auto-generated method stub
		
	}

	public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
		// TODO Auto-generated method stub
		
	}

	public void onTestFailure(ITestResult tr) {

		ITestContext context = tr.getTestContext();
        WebDriver driver = (WebDriver)context.getAttribute(Constants.CON_DRIVER_ATTR);
        
        try {
        	
            File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            
            String outputDir = Utils.getScreenshotDir();
            String filename = Constants.CON_SCREENSHOT_PREFIX + tr.getMethod().getMethodName() + ".png";
            
            File savedFile = new File(outputDir, filename);
            FileUtils.copyFile(screenshotFile, savedFile);
            
            // save screenshot path as result attribute so generateReport can access it
            tr.setAttribute("screenshotURL", filename);
            
        } catch (Exception e) {
			System.out.println("Error generating screenshot: " + e);
        }
	}

	public void onTestSkipped(ITestResult arg0) {
		// TODO Auto-generated method stub
		
	}

	public void onTestStart(ITestResult arg0) {
		// TODO Auto-generated method stub
		
	}

	public void onTestSuccess(ITestResult arg0) {
		// TODO Auto-generated method stub
		
	}
	
}	